package com.qst.order.controller;


import com.qst.order.domain.DTO.QueueMessage;
import com.qst.order.service.RabbitMQMonitorService;
import com.qst.order.utils.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * RabbitMQ监控控制器（队列管理、消息堆积监控）
 */
@RestController
@RequestMapping("/api/monitor/rabbitmq/queue")
@RequiredArgsConstructor
public class RabbitMQMonitorController {

    private final RabbitMQMonitorService rabbitMQMonitorService;

    /**
     * 获取队列消息数趋势
     * @param queueName 队列名称
     * @param timeRange 时间范围（分钟，默认60）
     */
    @GetMapping("/trend")
    public Result getQueueTrend(
            @RequestParam String queueName,
            @RequestParam(required = false, defaultValue = "60") int timeRange
    ) {

        try {
            List<String> timestamps = rabbitMQMonitorService.getQueueTrendTimestamps(queueName, timeRange);
            List<Integer> messageCounts = rabbitMQMonitorService.getQueueTrendMessageCounts(queueName, timeRange);
            Map<String, Object> map = new HashMap<>();
            map.put("timestamps", timestamps);
            map.put("messageCounts", messageCounts);
            return Result.success(map);
        } catch (Exception e) {
            return Result.error(500, "获取队列消息数趋势失败：" + e.getMessage());
        }

    }

    /**
     * 获取队列消息列表
     * @param queueName 队列名称
     * @param pageSize 最大条数（默认20）
     */
    @GetMapping("/messages")
    public Result getQueueMessages(
            @RequestParam String queueName,
            @RequestParam(required = false, defaultValue = "20") int pageSize
    ) {

        try {
            List<QueueMessage> messages = rabbitMQMonitorService.getQueueMessages(queueName, pageSize);
            return Result.success(messages);
        } catch (Exception e) {
            return Result.error(500, "获取队列消息列表失败：" + e.getMessage());
        }

    }

    /**
     * 清空队列
     */
//    @PostMapping("/clear")
//    public Result clearQueue(@RequestBody JSONObject param) {
//        JSONObject result = new JSONObject();
//        try {
//            String queueName = param.getString("queueName");
//            rabbitMQMonitorService.clearQueue(queueName);
//            result.put("code", 200);
//            result.put("msg", "队列清空成功");
//        } catch (Exception e) {
//            result.put("code", 500);
//            result.put("msg", e.getMessage());
//        }
//        return result;
//    }
}